package org.objective.base;

import org.objective.base.annotations.SingleInstanace;
import org.objective.base.annotations.TableMapping;
import org.objective.service.Loader;
import org.objective.service.Saver;

/**
 *
 * @author gus
 */
@TableMapping(mapper = BaseTypeInfo.class)
@SingleInstanace
public abstract class BaseType extends BaseDomainObject implements Storable
{
    protected final TypeModule ownerModule;

    protected BaseType(Storage storage, long id, TypeModule ownerModule)
    {
        super(storage, id);
        this.ownerModule = ownerModule;
    }

    public abstract String getDescription();

    @Override
    public abstract String getName();

    public abstract String getTypeName();

    public abstract void setTypeName(String name);

    public abstract Class getObjectType();

    public TypeModule getOwnerTypeModule()
    {
        return ownerModule;
    }

    public final BaseObject newInstance() throws Exception
    {
        return newInstance(null);
    }

    public BaseObject newInstance(ObjectInitializationCallback<BaseObject> callback) throws Exception
    {
        BaseObject object = storage.createObject(new Contructor());
        if (callback != null)
        {
            callback.initialze(object);
        }
        return object;
    }

    protected abstract BaseObject constructNewObject(long oid);

    @Override
    public boolean isReadOnly()
    {
        return true;
    }

    //  Once load on start application
    @Override
    public void loadData(Loader loader)
    {
    }

    @Override
    public void saveData(Saver saver) throws Exception
    {
        if (!storage.getLoader().existType(this))
        {
            BaseTypeInfo typeInfo = new BaseTypeInfo();
            typeInfo.setId(id);
            typeInfo.setUID(getUID());
            typeInfo.setName(getName());
            typeInfo.setDescription(getDescription());
            typeInfo.setLibraryName(getLibraryName());

            saver.insertType(typeInfo);
        }
    }

    @Override
    public Storable[] loadDepends()
    {
        return new Storable[0];
    }

    @Override
    public Storable[] saveDepends()
    {
        return new Storable[0];
    }

    private String getLibraryName()
    {
        return ownerModule.getLibraryName();
    }

    protected class Contructor implements Construction<BaseObject>
    {
        @Override
        public BaseObject constructObject(long oid)
        {
            return constructNewObject(oid);
        }

        @Override
        public Class getTypeCreation()
        {
            return getObjectType();
        }
    }
}

